<template>
    <ManagePage>
      <template #header>
        商品添加
      </template>
  
      <template #main>
        <el-form ref="form" :model="productForm" label-width="120px">
          <el-form-item label="商品类别">
            <el-select v-model="productForm.categoryId" placeholder="请选择商品类别">
              <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.name"
                :value="category.categoryId">
              </el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="商品名称">
            <el-input v-model="productForm.name"></el-input>
          </el-form-item>
  
          <el-form-item label="商品描述">
            <el-input type="textarea" v-model="productForm.description"></el-input>
          </el-form-item>
  
          <el-form-item label="商品价格">
            <el-input-number v-model="productForm.price" :min="0" :step="0.01"></el-input-number>
          </el-form-item>
  
          <el-form-item label="库存数量">
            <el-input-number v-model="productForm.inventory" :min="0"></el-input-number>
          </el-form-item>
  
          <el-form-item label="商品链接">
            <el-input v-model="productForm.link"></el-input>
          </el-form-item>
  
          <el-form-item label="商品图片">
            <el-upload
              action=""
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              :file-list="fileList"
              ref="upload">
              <i slot="default" class="el-icon-plus"></i>
              <template #file="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </template>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" @click="submitForm">立即创建</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </template>
    </ManagePage>
  </template>
  
  <script>
  import axios from '../../../axios/axios';
  import ManagePage from '../../Component/ManagePage.vue';
  
  export default {
    name: 'addProduct',
    components: {
      ManagePage,
    },
    data() {
      return {
        productForm: {
          categoryId: '',
          name: '',
          img: [],
          description: '',
          price: 0,
          inventory: 0,
          link: '',
        },
        categoryList: [],
        fileList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
      };
    },
    created() {
      this.fetchCategories();
    },
    methods: {
      async fetchCategories() {
        try {
          const response = await axios.get('/admin/category');
          if (Array.isArray(response)) {
            this.categoryList = response;
          } else {
            console.error('响应数据格式不正确:', response);
          }
        } catch (error) {
          console.error('获取类目列表失败', error);
        }
      },
      handleChange(file, fileList) {
        this.fileList = fileList;
      },
      handleRemove(file) {
        this.fileList = this.fileList.filter(item => item.uid !== file.uid);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      submitForm() {
        const formData = new FormData();
        formData.append('categoryId', this.productForm.categoryId);
        formData.append('name', this.productForm.name);
        formData.append('description', this.productForm.description);
        formData.append('price', this.productForm.price);
        formData.append('inventory', this.productForm.inventory);
        formData.append('link', this.productForm.link);
  
        this.fileList.forEach((file, index) => {
          formData.append(`img`, file.raw);
        });
  
        this.uploadProduct(formData);
      },
      async uploadProduct(formData) {
        try {
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
            transformRequest: [(data) => data], // 不要让 Axios 自动转换 FormData
          };
  
          const success = await axios.post('/product/creator/add', formData, config);
          if (success) {
            this.$message({
              type: 'success',
              message: '商品添加成功',
            });
            this.resetForm();
          } else {
            this.$message({
              type: 'warning',
              message: '商品添加失败，请重试',
            });
          }
        } catch (error) {
          console.error('添加商品失败', error.response ? error.response.data : error.message);
          this.$message({
            type: 'error',
            message: '添加商品失败，请检查网络连接',
          });
        }
      },
      resetForm() {
        this.productForm = {
          categoryId: '',
          name: '',
          img: [],
          description: '',
          price: 0,
          inventory: 0,
          link: '',
        };
        this.fileList = [];
        this.$refs.upload.clearFiles(); // 清除上传文件列表
      },
    },
  };
  </script>
  
  <style scoped>
  .el-upload--picture-card {
    line-height: 178px;
  }
  
  .el-upload-list__item {
    transition: none !important;
  }
  </style>
  
  
  
  